const fs = require('fs');
var unityPath = "";
var unityList = [];
var roleId = [];
var connectId = [];
readFile = () => {
    var config = JSON.parse(fs.readFileSync("./config.json", "utf8"));
    unityPath = config.cocosPrefabPath;
    const arr = fs.readdirSync(unityPath);
    arr.forEach((item) => {
        if (item.indexOf(".meta") == -1) {
            let d = fs.readFileSync(unityPath + "/" + item, "utf8");
            unityList.push(JSON.parse(d));
        }
    });
}
main = () => {
    readFile();
    for (var i = 0; i < unityList.length; i++) {
        roleId = [];
        connectId = [];
        getRoleId(unityList[i]);
        fs.writeFileSync(unityPath+"/"+ unityList[i][1]._name+".prefab", JSON.stringify(unityList[i]), (err) => {
            if (err) {
              console.error(err);
            }
        });
    }
}
getRoleId = (data)=>{
    for (var j = 0; j < data.length; j++) {
      if (data[j]._name == "role" && roleId.indexOf(j) == -1) {
            roleId.push(j);
            var raidId = getRaidId(data[j]._components,data);
            setConnectBody(raidId,data);
      }
    }
}
getRaidId = (data,data2) => {
    for(var i = 0;i<data.length;i++) {
        var id = data[i].__id__;
        if(data2[id].__type__ == "cc.RigidBody") return id;
    }
}
setConnectBody = (id,data)=>{
    for (var j = 0; j < data.length; j++) {
        if (data[j].__type__ == "cc.RopeJoint") {
            if(connectId.indexOf(j)==-1) {
                connectId.push(j);
                data[j].connectedBody = {
                    "__id__": id
                }
                return;
            }
        }
      }
}
main();